package com.gemalto.Kryptik.Gui;

import javax.swing.text.*;
import javax.swing.event.*; 
import java.awt.Toolkit; 

public class HexDocument extends PlainDocument { 

    private int maxChars; 
    int length=0;
    private String allowedChars = "ABCDEFabcdef0123456789 ";


    public HexDocument(){ this(0);}

    public HexDocument(int maxChars) {
	this.maxChars = maxChars;
    } 
    
    public void setMaxLength(int max){
        this.maxChars = max;
    }
    

    public int countSpaces(int endPos){
	String s="";
	try {
	  s=getText(0,endPos);
	} catch (BadLocationException e){
	  System.out.println(e.getMessage());
	}
	int i=0;
	int index=s.indexOf(' ');
	while (index!=-1){
	  i++;
	  index=s.indexOf(' ',index+1);
	}
	return i;
    }	  

    public void insertString(int offset, String s, AttributeSet a) throws BadLocationException {
	StringBuffer sb=new StringBuffer();
        if (maxChars > 0 && getLength() - countSpaces(getLength()) + s.length() > maxChars) {
            Toolkit.getDefaultToolkit().beep();
            return;
        }
        for (int i=0;i<s.length();i++){
            if (allowedChars.indexOf(s.charAt(i))>-1){
                 sb.append(s.charAt(i));
                 if ((offset+i+1-countSpaces(offset+i))%8==0) sb.append(' ');
	    }  //else sb.append(" ");
	}
       super.insertString(offset,sb.toString().toUpperCase(),a); 
    } 



} 
